//
//  ShoppingViewController.m
//  Mall
//
//  Created by 孙飞燕 on 16/9/28.
//  Copyright © 2016年 孙飞燕. All rights reserved.
//

#import "ShoppingViewController.h"
@interface ShoppingViewController ()<UITableViewDelegate,UITableViewDataSource,ShopCarBottomViewDelegate,ShopCarTableViewCellDelagate>
{
    float allPrice;

}
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataSourceArr;//用来存储加入到购物车的商品
@property (nonatomic,assign)BOOL isEditing;//是否编辑
@property (nonatomic,assign)BOOL isAllSel;//全选按钮

@property (nonatomic,strong)ShoppingCarBottomModel *bottomModel;

@property (nonatomic,strong)NSMutableArray *infoArr;

@end

@implementation ShoppingViewController
- (NSMutableArray *)infoArr{
    if (!_infoArr) {
        _infoArr = [[NSMutableArray alloc]init];
        for (int i = 0; i<4; i++) {
            NSMutableDictionary *infoDic = [[NSMutableDictionary alloc]init];
            [infoDic setValue:@"k0" forKey:@"goodsImage"];

            [infoDic setValue:@"这是商品标题" forKey:@"goodsTitle"];

            [infoDic setValue:@"2000" forKey:@"goodsPrice"];

            [infoDic setValue:[NSNumber numberWithBool:NO] forKey:@"selectState"];

            [infoDic setValue:[NSNumber numberWithInt:1] forKey:@"goodsNum"];
             //封装数据模型
            GoodsModel *model = [[GoodsModel alloc]initWithDict:infoDic];
            //将数据模型放入数组中
            [_infoArr addObject:model];
            
        }
        NSLog(@"-------------%@",_infoArr);

    }
    return _infoArr;
}
- (NSMutableArray *)dataSourceArr{
    if (!_dataSourceArr) {
        _dataSourceArr = [[NSMutableArray alloc]init];
    }
    return _dataSourceArr;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,kWidth, kHeight - 50)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //注册cell
        [_tableView registerNib:[UINib nibWithNibName:@"ShopCarTableViewCell" bundle:nil] forCellReuseIdentifier:@"ShopCarTableViewCell"];
        _tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的订单";
    [self.view addSubview:self.tableView];
    //导航栏右侧添加编辑按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editAction:)];
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];

    [self setUpBottomView];




}

//导航栏编辑按钮回调方法
- (void)editAction:(UIBarButtonItem *)sender{
    if (!self.isEditing) {
        //允许多个编辑
        self.tableView.allowsMultipleSelectionDuringEditing = YES;
        //允许编辑
        self.tableView.editing = YES;
        [sender setTitle:@"完成"];
    }else{
        [sender setTitle:@"编辑"];
        //放置要删除的对象
        NSMutableArray *deleteArr = [[NSMutableArray alloc]init];
        //要删除的row
        NSArray *selectedArr = [self.tableView indexPathsForSelectedRows];
        for (NSIndexPath *indexPath in selectedArr) {
            [deleteArr addObject:self.dataSourceArr[indexPath.row]];
        }
        //先删除数据源
        [self.infoArr removeObjectsInArray:deleteArr];
        //再删除UI
        [self.tableView deleteRowsAtIndexPaths:selectedArr withRowAnimation:UITableViewRowAnimationNone];
        //关掉编辑
        self.tableView.editing = NO;
    }
    self.isEditing = !self.isEditing;
}
#pragma mark --- UITableView的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 //    return self.dataSourceArr.count;
    return self.infoArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShopCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShopCarTableViewCell" forIndexPath:indexPath];
    cell.delegate = self;
    [cell addTheValue:self.infoArr[indexPath.row]];
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
}

//设置底部View
- (void)setUpBottomView{
    ShopCarBottomView *bottomView = [[ShopCarBottomView alloc]initWithFrame:CGRectMake(0, self.tableView.frame.size.height- 50, self.tableView.frame.size.width, 50) withModel:self.bottomModel];
    bottomView.delegate = self;

    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];

    [self.tableView reloadData];

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 判断当期是否为选中状态，如果选中状态点击则更改成未选中，如果未选中点击则更改成选中状态
    GoodsModel *model = self.infoArr[indexPath.row];
    if (model.selectState) {
        model.selectState = NO;
    }else{
        model.selectState = YES;
    }

    //刷新当前行
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

    [self totalPrice];
}

/**
 *  cell的代理方法
 *
 *  @param cell     cell可以拿到indexpath
 *  @param selectBtn 选中按钮
 */
- (void)shopCarTableViewCellDelegate:(ShopCarTableViewCell *)cell withSelectButton:(UIButton *)selectBtn{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    GoodsModel *model = self.infoArr[indexPath.row];
    model.selectState = !selectBtn.selected;
    int counts = 0;
    for (GoodsModel *modelArr in self.infoArr) {
        if (modelArr.selectState) {
            counts ++;
        }
    }
    [self isAllSelectAllPrice];
    [self.tableView reloadData];
}

/**
 *  遍历所有是否全选
 */
- (void)isAllSelectAllPrice{

        for (GoodsModel *model in self.infoArr) {
            if (!model.selectState) {
                self.bottomModel.isSelect = NO;
                return;
            }else{
                self.bottomModel.isSelect = YES;
            }
        }

}
//全选按钮的代理方法
- (void)shopCarBottomViewDelegate:(UIButton *)allSelectBtn withView:(ShopCarBottomView *)view{
    //判断是否选中，是改成否，否改成是，改变图片状态
//    allSelectBtn.tag = !allSelectBtn.tag;

    allSelectBtn.selected = !allSelectBtn.selected;
    self.bottomModel.isSelect = allSelectBtn.selected;
    if (allSelectBtn.selected) {
        self.isAllSel = YES;
    }else{
        self.isAllSel = NO;
    }
    //逻辑
    if (self.isAllSel) {
        for (GoodsModel *model in self.infoArr) {
            model.selectState = YES;
        }
    }else{
        for (GoodsModel *model in self.infoArr) {
            model.selectState = NO;
        }
    }

    if (allSelectBtn.selected)
    {
        [allSelectBtn setImage:[UIImage imageNamed:@"btn_selected"]   forState:UIControlStateNormal];
    }else{
        [allSelectBtn setImage:[UIImage imageNamed:@"btn_selected_default"] forState:UIControlStateNormal];
    }
    //改变单元格选中状态
    for (int i = 0; i<self.infoArr.count; i++) {
        GoodsModel *model = [self.infoArr objectAtIndex:i];
        model.selectState = allSelectBtn.selected;
    }

    //计算价格
    [self totalPrice];
    view.resultPrice.text = [NSString stringWithFormat:@"%.2f",allPrice];

    //每次算完要重置为0，因为每次的都是全部循环算一遍
    allPrice = 0.0;
    //刷新表格
    [self.tableView reloadData];
}

//计算价格
- (void)totalPrice{
    //遍历整个数据源，然后判断如果是选中的商品，就计算价格（单价 * 商品数量）
    for ( int i = 0; i<self.infoArr.count; i++){
        GoodsModel *model = [self.infoArr objectAtIndex:i];
        if (model.selectState){
            allPrice = allPrice + model.goodsNumber *[model.goodsPrice intValue];
        }
    }

    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
